package dao;

import model.User;
import utils.DBHelper;

import java.sql.ResultSet;

/**
 * @ClassName UserDao
 * @Description TODO
 * @Author 15965
 * @Date 2023/5/4 15:27
 * @Version 1.0
 */
public class UserDao {
    private final DBHelper dbHelper = DBHelper.getDBHelper();

    public User getUserByUsername(String username) {
        User user = null;
        try {
            String selectUserByUsernameSql = "select id, username, password from user where username=?";
            System.out.println("sql: " + selectUserByUsernameSql);
            ResultSet rs = dbHelper.executeQuery(selectUserByUsernameSql, username);
            if (rs.next()) {
                int id = rs.getInt("id");
                String pwd = rs.getString("password");
                user = new User(id, username, pwd);
            }
            rs.close();
        } catch (Exception e) {
            System.out.println("查询数据库异常！！！");
            e.printStackTrace();
        }
        return user;
    }

    public int insert(String username, String password) {
        User user = new User(username, password);
        String sql = "insert into User (username, password) values (?,?);";
        int res = 0;
        try {
            res = dbHelper.executeUpdate(sql, user.getUsername(), user.getPassword());
        } catch (Exception e) {
            System.out.println("写入数据库异常！！！");
            e.printStackTrace();
        }
        return res;
    }
}
